<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>图片压缩工具</title>
  <link rel="stylesheet" href="index.css">
</head>

<body>
  <div class="window card" draggable="true" id="drag">
    <div class="window-head">图片压缩工具</div>
    <!-- <div class="card"></div> -->
    <button onclick="windowClose()">关闭</button>
    <button onclick="openDevTools()">打开调试器</button>
    <br>
    <textarea name="" id="" cols="30" rows="10" autocomplete="off" readonly style="resize:none;width: 95%;" ></textarea>
    <button onclick="startCompression()" class="start-btn">开始压缩</button>
  </div>


  <script>
    const { ipcRenderer } = require('electron')
    const {readdir, readFile, writeFile } = require('node:fs/promises')
    const axios = require('axios')

    function windowClose() {
      ipcRenderer.send('window-close')
    }

    function openDevTools() {
      ipcRenderer.send('window-openDevTools')
    }

    dragEl = document.getElementById('drag')

    function dragover(e) {
      e.stopPropagation()
      e.preventDefault()
    }
    dragEl.addEventListener('dragover', dragover)
    dragEl.addEventListener('dragenter', dragover)
    let fileArray = []
    dragEl.addEventListener('drop', async function (e) {
      dragover(e)
      if (this.loading) return
      fileArray = []
      var files = e.dataTransfer.files
      console.log(files)
      // 加载文件
      let str = ''
      for (let i = 0; i < files.length; i++) {
        let path = files[i].path.replace(/\\/g, '/')
        if(files[i].type !== '') {
          // 文件
          str += path + '\n'
          fileArray.push({path})
        } else {
          // 文件夹
          const files2 = await readdir(path)
          for (let j = 0; j < files2.length; j++) {
            let path2 = path + '/' + files2[j]
            if(files2[j].type !== '') {
              str += path2 + '\n'
              fileArray.push({path: path2})
            }
          }
        }
        
      }
      document.querySelector('textarea').value = str
      console.log(fileArray);
    })

    // 压缩
    async function startCompression(){
      if(fileArray.length === 0) return alert('请先选择文件')
      // let tasks = []
      let btn = document.querySelector('.start-btn')
      btn.disabled = true

      for (let i = 0; i < fileArray.length; i++) {
        if(!fileArray[i].isRun) {
          await compressionFile(i)
        }
      }

      btn.disabled = false
      alert('压缩完毕')
      
    }

    function compressionFile(i){
      return new Promise(async (resolve, reject)=>{
        try {
          fileArray[i].isRun = true
          let data = await readFile(fileArray[i].path)
          let headers = {
            'Origin': 'https://tinypng.com',
            'Referer': 'https://tinypng.com/',
            'Content-Type': 'image/jpeg'
          }
          const {data: res } = await axios.post('https://tinypng.com/web/shrink', data, headers)
          let url = res.output.url
          if(!url) return
          let {data: res2} = await axios.get(url, { responseType: 'arraybuffer' })
          res2 = new Uint8Array(res2)
          const res3 = await writeFile(fileArray[i].path, res2)
          fileArray[i].isRun = false
          resolve('ok')
        } catch (error) {
          resolve('no')
        }
      })
    }
  </script>
</body>

</html>